// PackageRemapper.groovy
package com.kasax.plugin.shadow

import org.objectweb.asm.commons.Remapper
import org.objectweb.asm.Opcodes
import com.kasax.plugin.shadow.utils.LogUtils
class PackageRemapper extends Remapper {

    private final Map<String, String> mapping

    PackageRemapper(Map<String, String> mapping) {
        this.mapping = mapping
        LogUtils.d("PackageRemapper", "PackageRemapper initialized with mapping: ${mapping.size()} entries")
    }

    @Override
    String map(String internalName) {
        if (!internalName) return internalName
        mapping[internalName] ?: internalName
    }

    @Override
    String mapDesc(String descriptor) {
        if (!descriptor) return descriptor
        def sb = new StringBuilder(descriptor.length())
        for (int i = 0; i < descriptor.length(); ) {
            char c = descriptor.charAt(i++)
            if (c == 'L') {
                int j = descriptor.indexOf(';', i)
                if (j == -1) return descriptor
                def old = descriptor.substring(i - 1, j + 1)
                def m = map(old)
                sb.append(m ?: old)
                i = j + 1
            } else if (c == '[') {
                sb.append(c)
            } else {
                sb.append(c)
            }
        }
        return sb.toString()
    }

    @Override
    String mapMethodName(String owner, String name, String descriptor) {
        def newOwner = map(owner)
        return newOwner == owner ? name : name  // 需要改方法名时再扩展
    }

    @Override
    String mapFieldName(String owner, String name, String descriptor) {
        def newOwner = map(owner)
        return newOwner == owner ? name : name // 需要改字段名时再扩展
    }

//    @Override
//    String mapAnnotationDescriptor(String descriptor) {
//        return mapDesc(descriptor)
//    }

    @Override
    String[] mapTypes(String[] types) {
        if (!types) return types
        return types.collect { map(it) } as String[]
    }
}